"""
@人脸识别API
"""
import logging
import uuid
from datetime import datetime
from flask import request, Blueprint
from flask_jwt_extended import get_jwt_identity, jwt_required
from base.tools.develop_tools import JsonResult, phone_check, rand_num, login_required
from service.api import API
from base.wx_pay.wx_pay import WXPAY


blueprint = Blueprint("face_verify", __name__, url_prefix="/personal/face/verify/")
logger = logging.getLogger("face_verify")


@blueprint.route("/create_order", methods=["POST"])
@jwt_required()
def create_order():
    try:
        user_id = get_jwt_identity()
        obj = FaceOrderAPI()
        pay_info = obj.create_order(user_id=user_id)
        return JsonResult.ok("订单创建成功!", pay_info)
    except Exception as e:
        logger.exception(f"订单创建失败!{str(e)}")
        return JsonResult.error("订单创建失败!")


class FaceOrderAPI(API):
    def __init__(self) -> None:
        super().__init__()
        self.wx_pay = WXPAY()
        self.table = self._mongo["order_info"]
        self.order_type = 'face_verify'
        self.price = 1
        self.desc = "布零布零-人脸验证"
        self.callback = "https://linglongge.online/face/verify/callback"

    def create_order(self, user_id):
        order_id = str(uuid.uuid4())[:20]
        info = self.wx_pay.get_pay_id(order_id=order_id, desc=self.desc,
                                           price=self.price, callback=self.callback, open_id=user_id, attach=self.order_type)
        self.table.insert_one({
            "order_id": order_id,
            "user_id": user_id,
            "price":  self.price,
            "create_time": datetime.now(),
            "is_pay": False,
            "order_type": self.order_type
        })
        return info
